/*
*  Eve Calendar Import Project
*  Copyright (C) 2011  EveCal Project
*  Contact martinc@riseup.net
*
*   This program is free software; you can redistribute it and/or modify
*   it under the terms of the GNU General Public License as published by
*   the Free Software Foundation; either version 3 of the License, or
*   (at your option) any later version.
*
*   This program is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU General Public License for more details.
*
*   You should have received a copy of the GNU General Public License
*   along with this program; if not, write to the Free Software Foundation,
*   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
*   
*
*/

package calanderExport;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.ListIterator;
import java.util.TimeZone;

import javax.swing.JButton;
import javax.swing.JCheckBox;

import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import com.beimin.eveapi.character.calendar.upcomingevents.ApiUpcomingCalendarEvent;
import com.beimin.eveapi.character.calendar.upcomingevents.UpcomingCalendarEventsParser;
import com.beimin.eveapi.character.calendar.upcomingevents.UpcomingCalendarEventsResponse;
import com.beimin.eveapi.core.ApiAuthorization;
import com.beimin.eveapi.core.ApiException;
import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarQuery.ExtendedPropertyMatch;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Link;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.data.extensions.When;
import com.google.gdata.util.ServiceException;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class EveCalender extends javax.swing.JPanel {
	private static ECalConfig config = null;
	private static final String confLoc = "EveCal.xml";
	private JLabel UserLabel;
	private static JFrame frame;
	private JTextField GUser;
	private JPasswordField GPass;
	private JLabel jLabel5;
	private JButton RunImport;
	private JTextField CharID;
	private JTextField APIKey;
	private JLabel jLabel4;
	private JTextField UserID;
	private JLabel jLabel3;
	private JTextField CalLoc;
	private JLabel jLabel2;
	private JLabel jLabel1;
	private static String googleUser;
	private static String googlePass;
	private static String apiKey;
	private static String calenderAddress;
	private static long characterid;
	private static int userid;
	/**
	* Auto-generated main method to display this 
	* JPanel inside a new JFrame.
	*/
	public static void main(String[] args) {
		try {
			
		} catch (Exception e) {
			
		}
		frame = new JFrame();
		frame.getContentPane().add(new EveCalender());
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.pack();
		frame.setVisible(true);
	}
	
	public EveCalender() {
		super();
		initGUI();
	}
	
	private void initGUI() {
		try {
			this.setPreferredSize(new java.awt.Dimension(502, 264));
			this.setLayout(null);
			{
				UserLabel = new JLabel();
				this.add(UserLabel);
				UserLabel.setText("Google User:");
				UserLabel.setBounds(18, 21, 134, 14);
			}
			{
				GUser = new JTextField();
				this.add(GUser);
				GUser.setBounds(184, 18, 228, 21);
			}
			{
				jLabel1 = new JLabel();
				this.add(jLabel1);
				jLabel1.setText("Google Password");
				jLabel1.setBounds(18, 47, 134, 14);
			}
			{
				GPass = new JPasswordField();
				this.add(GPass);
				GPass.setBounds(184, 44, 228, 21);
			}
			{
				jLabel2 = new JLabel();
				this.add(jLabel2);
				jLabel2.setText("Calendar Location");
				jLabel2.setBounds(18, 73, 134, 14);
			}
			{
				CalLoc = new JTextField();
				this.add(CalLoc);
				CalLoc.setBounds(184, 70, 228, 21);
			}
			{
				jLabel3 = new JLabel();
				this.add(jLabel3);
				jLabel3.setText("Eve User ID");
				jLabel3.setBounds(18, 99, 134, 14);
			}
			{
				UserID = new JTextField();
				this.add(UserID);
				UserID.setBounds(184, 96, 228, 21);
			}
			{
				jLabel4 = new JLabel();
				this.add(jLabel4);
				jLabel4.setText("API Key");
				jLabel4.setBounds(18, 125, 134, 14);
			}
			{
				APIKey = new JTextField();
				this.add(APIKey);
				APIKey.setBounds(184, 122, 228, 20);
			}
			{
				jLabel5 = new JLabel();
				this.add(jLabel5);
				jLabel5.setText("Character ID");
				jLabel5.setBounds(12, 151, 140, 14);
			}
			{
				CharID = new JTextField();
				this.add(CharID);
				CharID.setBounds(184, 150, 228, 17);
			}
			{
				RunImport = new JButton();
				this.add(RunImport);
				RunImport.setText("Import Data");
				RunImport.setBounds(152, 217, 108, 29);
				RunImport.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						RunImportActionPerformed(evt);
					}
				});
			}
			if(GetConfig()) {

				GUser.setText(config.getGoogleUser());
				GPass.setText(config.getGooglePass());
				CalLoc.setText(config.getCalLoc());
				UserID.setText(String.valueOf(config.getUserID()));
				APIKey.setText(config.getAPIKey());
				CharID.setText(String.valueOf(config.getCharacterID()));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void RunImportActionPerformed(ActionEvent evt) {
		if(GUser.getText().length() > 0) {
			googleUser = GUser.getText();
		}
		if (GPass.getText().length() > 0) {
			googlePass = GPass.getText();
		}
		if (APIKey.getText().length() > 0) {
			apiKey = APIKey.getText();
		}
		if(CalLoc.getText().length() > 0) {
			calenderAddress = CalLoc.getText();
		}
		if(CharID.getText().length() > 0) {
			characterid = Long.parseLong(CharID.getText());
		}
		if(UserID.getText().length() > 0) {
			userid = Integer.parseInt(UserID.getText());
		}
		config = new ECalConfig();
		int count = RunUpdate();
		 JOptionPane.showMessageDialog(frame,"Added " + count + " Events");
		config.setAPIKey(apiKey);
		config.setCalLoc(calenderAddress);
		config.setCharacterID(characterid);
		config.setGoogleUser(googleUser);
		config.setUserID(userid);
		SaveConfig();


	}
	public int RunUpdate() {
		ListIterator<ApiUpcomingCalendarEvent> runner = null;
		List<ApiUpcomingCalendarEvent> events = null;
		UpcomingCalendarEventsResponse sr = null;
		UpcomingCalendarEventsParser sp = null;
		ApiAuthorization apiau = null;
		Date thEnd = null;
		GregorianCalendar tCal = new GregorianCalendar();
		apiau = new ApiAuthorization(userid, characterid, apiKey);
		sp = new UpcomingCalendarEventsParser();
		try {
			sr = sp.getResponse(apiau);
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(frame, e.getMessage());
			return 0;
		}
		delEvents();
		events = sr.getUpcomingCalendarEvents();
		ApiUpcomingCalendarEvent event;
		int i = 0;
		runner = events.listIterator();

		while(runner.hasNext()) {
			event = (ApiUpcomingCalendarEvent) runner.next();
			tCal.setTime(event.getEventDate());
			tCal.add(Calendar.MINUTE, event.getDuration());
			Date EndDate = tCal.getTime();
			insert(event.getEventDate(), EndDate, event.getEventTitle(), event.getEventText());
			i ++;
		}
		return i;
		
	}

	private void delEvents() {
		CalendarService myService = null;
		URL postURL = null;
		myService = new CalendarService("CalanderExport");
		try {
			myService.setUserCredentials(googleUser, googlePass);
		}catch (Exception e) {
			
		}
		try {
			postURL = new URL(calenderAddress);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(frame, e.getMessage());
		}
		CalendarQuery Query = new CalendarQuery(postURL);
		Query.setMinimumStartTime(new DateTime(new Date()));
		Query.setExtendedPropertyQuery(new ExtendedPropertyMatch("created", "ecal"));
		CalendarEventFeed Results;
		try {
			Results = myService.query(Query, CalendarEventFeed.class);
			int i = 0;
			while (Results.getEntries().size() > i) {
				CalendarEventEntry delentry = (CalendarEventEntry) Results.getEntries().get(i);
				delentry.delete();
				i ++;
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(frame, e.getMessage());
		}

	}


	@SuppressWarnings("deprecation")
	public static Link insert (Date Start, Date End, String Title, String Description) {
		CalendarService myService = null;
		URL postURL = null;
		
		myService = new CalendarService("EveCal");
		try {
			myService.setUserCredentials(googleUser, googlePass);
		}catch (Exception e) {
			JOptionPane.showMessageDialog(frame, e.getMessage());
			
		}
		try {
			postURL = new URL(calenderAddress);
			
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(frame, e1.getMessage());
		}
		DateTime startTime = new DateTime(Start);
		DateTime endTime = new DateTime(End);
		When eventTimes = new When();
		eventTimes.setStartTime(startTime);
		eventTimes.setEndTime(endTime);
		CalendarEventEntry Entry = new CalendarEventEntry();
		Entry.setTitle(new PlainTextConstruct(Title));
		ExtendedProperty created = new ExtendedProperty();
		created.setName("created");
		created.setValue("ecal");
		Entry.addExtendedProperty(created);
		Entry.setContent(new PlainTextConstruct(Description));
		Entry.addTime(eventTimes);

	// Send the request and receive the response:
		try {
			CalendarEventEntry insertedEntry = myService.insert(postURL, Entry);

			return insertedEntry.getEditLink();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(frame, e.getMessage());
		}
		return null;
		
	}
	public static boolean GetConfig() {
		FileInputStream fis = null;
		XMLDecoder decoder = null;
//		ObjectInputStream in = null;
		try {
			fis = new FileInputStream(confLoc);
			decoder = new XMLDecoder(fis);
			config = (ECalConfig)decoder.readObject();
			decoder.close();
		}
		catch(Exception e) {
			return false;
		}
		return true;
	}
	
	public boolean SaveConfig() {
		FileOutputStream fos = null;
		XMLEncoder encoder = null;
		try {
			fos = new FileOutputStream(confLoc);
			encoder = new XMLEncoder(fos);
			encoder.writeObject(config);
			encoder.close();
		} catch (Exception e) {
			return false;
		}
		return true;
	}


}
